<template>
    <rx-popover class="rx-select" tabindex="-1" :type="'fixed'" :placement="'bottom-start'" ref="popover">
        <div class="rx-select-value"
        :class="{
          'is-placeholder':!value
        }">{{label||placeholder}}</div>
        <div slot="popover">
           <slot name="beforelist"></slot>
           <ul class="rx-select-list">
            <li class="rx-select-list__item" v-for="item in list"
              :value="item[optionValue]" :key="item[optionValue]" @click="updateValue(item[optionValue],item)"
              :class="{
                'is-active':item[optionValue]===value
              }">{{item[optionLabel]}}</li>
            <li class="rx-select-list__item-nodata" v-if="list.length==0">暂无数据。</li>
           </ul>
           <slot name="afterlist"></slot>
        </div>
    </rx-popover>
</template>
<script>
export default {
    name:'rx-selecter',
    props:{
        placeholder:{
            type:String,
            default(){
                return '请选择'
            }
        },
        list:{
          type:Array,
          default(){
            return [];
          }
        },
        value:{
          default:''
        },
        disabled:{
          type:Boolean,
          default(){
            return false;
          }
        },
        optionValue:{
          type:String,
          default(){
            return 'id';
          }
        },
        optionLabel:{
          type:String,
          default(){
            return 'name';
          }
        }
    },
    computed:{
      label(){
        try {
           return this.value?this.list.find((item)=>{
              return item[this.optionValue]===this.value;
           })[this.optionLabel]:'';
        } catch (error) {
          console.error('select 未找打当前值选项，是不是被删了？');
          return '';
        }
       
      }
    },
    methods:{
      updateValue(nval,item){
        this.$emit('input',nval);
        if(this.value!==nval){
          this.$emit('change',item);
        }
        this.$refs.popover.hide();
      }
    }
}
</script>
<style lang="scss">
.rx-select:focus{
  outline: none;

  .rx-select-value{
    border-color: #3673ff;
  }
}
.rx-select-value{
  line-height: 1;
  padding: 6px;
  min-width: 100px;
  user-select: none;
  cursor: default;
  border: 1px solid #C4CAD7;
  border-radius: 4px;
  background-color: #fff;

  &.is-placeholder{
    color: #aaa;
  }
}
.rx-select-list{
  list-style-type: none;
  padding: 6px 0;
  overflow: auto;
  max-height: calc(50vh - 40px);
  background-color: #fff;

  border: 1px solid #DEE4EE;
  border-radius: 4px;
}
.rx-select-list__item{
  padding: 0 10px;
  cursor: default;

  &:hover{
    background: #F1F5FF;
  }
  &.is-active{
    color: #3673FF;
  }
}
.rx-select-list__item-nodata{
  padding: 0 10px;
  cursor: default;
}
</style>


